package com.guojing.jl.nio.channel;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;


public class TestFileChannelTransferTo {

    @Test
    public void test1() {
        try {
            FileChannel from = new FileInputStream("data.txt").getChannel();
            FileChannel to = new FileOutputStream("to.txt").getChannel();
            // 效率高，底层会利用操作系统的零拷贝进行优化, 最大支持2g 数据
             from.transferTo(0,  from.size(), to);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        try {
            FileChannel from = new FileInputStream("data.txt").getChannel();
            FileChannel to = new FileOutputStream("to.txt").getChannel();
            // 效率高，底层会利用操作系统的零拷贝进行优化, 最大支持2g 数据，通过下面的多次写入来支持大文件
            long size = from.size();

            // left 变量代表还剩余多少字节
            for (long left = size; left > 0; ) {
                System.out.println("position:" + (size - left) + " left:" + left);
                left = left - from.transferTo((size - left), left, to);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
